<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>时间分析</title>
    <!-- 使用更可靠的CDN源 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f0f0;
        }
        .nav {
            background-color: #333;
            overflow: hidden;
            padding: 0 20px;
        }
        .nav a {
            float: left;
            color: white;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
            font-size: 17px;
        }
        .nav a:hover {
            background-color: #ddd;
            color: black;
        }
        .nav a.active {
            background-color: #4CAF50;
            color: white;
        }
        .container {
            padding: 2rem;
            max-width: 1200px;
            margin: 0 auto;
        }
        .chart-container {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            padding: 1rem;
            margin-bottom: 2rem;
            position: relative;
            min-height: 300px;
        }
        .chart-title {
            text-align: center;
            color: #333;
            margin-bottom: 1rem;
        }
        canvas {
            max-height: 400px;
        }
        .error-message {
            color: red;
            text-align: center;
            padding: 1rem;
            display: none;
        }
        .loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="nav">
        <a href="index.html">计时器</a>
        <a href="records.html">记录</a>
        <a href="analysis.html" class="active">分析</a>
    </div>

    <div class="container">
        <div class="chart-container">
            <h2 class="chart-title">每日时间分布</h2>
            <div class="loading" id="dailyChartLoading">加载中...</div>
            <div class="error-message" id="dailyChartError"></div>
            <canvas id="dailyChart"></canvas>
        </div>

        <div class="chart-container">
            <h2 class="chart-title">活动时间占比</h2>
            <div class="loading" id="pieChartLoading">加载中...</div>
            <div class="error-message" id="pieChartError"></div>
            <canvas id="activityPieChart"></canvas>
        </div>

        <div class="chart-container">
            <h2 class="chart-title">近期时间趋势</h2>
            <div class="loading" id="trendChartLoading">加载中...</div>
            <div class="error-message" id="trendChartError"></div>
            <canvas id="trendChart"></canvas>
        </div>
    </div>

    <script>
        // 检查Chart.js是否成功加载
        if (typeof Chart === 'undefined') {
            alert('图表库加载失败，请检查网络连接后刷新页面');
        }

        function parseTime(timeStr) {
            const [hours, minutes, seconds] = timeStr.split(':').map(Number);
            return hours * 3600 + minutes * 60 + seconds;
        }

        function formatHours(seconds) {
            return (seconds / 3600).toFixed(1);
        }

        function hideLoading(chartId) {
            document.getElementById(chartId + 'Loading').style.display = 'none';
        }

        function showError(chartId, message) {
            const errorElement = document.getElementById(chartId + 'Error');
            errorElement.textContent = message;
            errorElement.style.display = 'block';
            hideLoading(chartId);
        }

        async function loadAndAnalyzeData() {
            try {
                const response = await fetch('/api/records');
                if (!response.ok) {
                    throw new Error('获取数据失败');
                }
                const records = await response.json();

                if (!records || records.length === 0) {
                    ['daily', 'pie', 'trend'].forEach(chartId => {
                        showError(chartId + 'Chart', '暂无数据');
                    });
                    return;
                }

                // 处理数据
                const activityData = {};
                const dailyData = {};
                const trendData = {};

                records.forEach(record => {
                    const timeStr = record.duration.replace('时长: ', '');
                    const activity = record.activity.replace('活动: ', '');
                    const seconds = parseTime(timeStr);
                    const hours = seconds / 3600;
                    const date = record.date.split(' ')[0];

                    // 活动统计
                    if (activityData[activity]) {
                        activityData[activity] += hours;
                    } else {
                        activityData[activity] = hours;
                    }

                    // 每日统计
                    if (dailyData[date]) {
                        dailyData[date] += hours;
                    } else {
                        dailyData[date] = hours;
                    }

                    // 趋势统计
                    trendData[date] = (trendData[date] || 0) + hours;
                });

                try {
                    // 创建饼图 - 活动时间占比
                    const pieCtx = document.getElementById('activityPieChart').getContext('2d');
                    new Chart(pieCtx, {
                        type: 'pie',
                        data: {
                            labels: Object.keys(activityData),
                            datasets: [{
                                data: Object.values(activityData),
                                backgroundColor: [
                                    '#FF6384',
                                    '#36A2EB',
                                    '#FFCE56',
                                    '#4BC0C0',
                                    '#9966FF',
                                    '#FF9F40'
                                ]
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'right'
                                },
                                title: {
                                    display: true,
                                    text: '各活动时间占比（小时）'
                                }
                            }
                        }
                    });
                    hideLoading('pieChart');
                } catch (error) {
                    showError('pieChart', '图表创建失败');
                    console.error('饼图创建失败:', error);
                }

                try {
                    // 创建柱状图 - 每日时间分布
                    const dailyCtx = document.getElementById('dailyChart').getContext('2d');
                    new Chart(dailyCtx, {
                        type: 'bar',
                        data: {
                            labels: Object.keys(dailyData),
                            datasets: [{
                                label: '时间（小时）',
                                data: Object.values(dailyData),
                                backgroundColor: '#4CAF50'
                            }]
                        },
                        options: {
                            responsive: true,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    title: {
                                        display: true,
                                        text: '小时'
                                    }
                                }
                            }
                        }
                    });
                    hideLoading('dailyChart');
                } catch (error) {
                    showError('dailyChart', '图表创建失败');
                    console.error('柱状图创建失败:', error);
                }

                try {
                    // 创建折线图 - 时间趋势
                    const trendCtx = document.getElementById('trendChart').getContext('2d');
                    const sortedDates = Object.keys(trendData).sort();
                    new Chart(trendCtx, {
                        type: 'line',
                        data: {
                            labels: sortedDates,
                            datasets: [{
                                label: '每日时间（小时）',
                                data: sortedDates.map(date => trendData[date]),
                                borderColor: '#2196F3',
                                tension: 0.1
                            }]
                        },
                        options: {
                            responsive: true,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    title: {
                                        display: true,
                                        text: '小时'
                                    }
                                }
                            }
                        }
                    });
                    hideLoading('trendChart');
                } catch (error) {
                    showError('trendChart', '图表创建失败');
                    console.error('折线图创建失败:', error);
                }

            } catch (error) {
                console.error('加载数据失败:', error);
                ['daily', 'pie', 'trend'].forEach(chartId => {
                    showError(chartId + 'Chart', '数据加载失败，请刷新页面重试');
                });
            }
        }

        // 页面加载时获取并分析数据
        loadAndAnalyzeData();
    </script>
</body>
</html> 